﻿using Microsoft.Experimental.IO;
using System.IO;
using System.Web;
using up7.db.model;

namespace up7.db.utils
{
    /// <summary>
    /// 文件块处理器
    /// 优化文件创建逻辑，按文件实际大小创建
    /// </summary>
    public class FileBlockWriter
	{
		public FileBlockWriter()
		{
		}

		/// <summary>
		/// 根据文件大小创建文件。
		/// </summary>
		public void make(string filePath,long len)
		{
            //文件不存在则创建
            if (string.IsNullOrEmpty(filePath)) return;
			if (!LongPathFile.Exists(filePath))
            {
                var pos = filePath.LastIndexOf('\\');
                if (-1 == pos) pos = filePath.LastIndexOf('/');
                var dir = filePath.Substring(0, pos);
                //自动创建目录
                if (!LongPathDirectory.Exists(dir))
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("路径不存在：{0}", dir));
                    PathTool.createDirectory(dir);
                }

                //创建文件
                var fs = LongPathFile.Open(filePath,FileMode.Create, FileAccess.Write);
                fs.SetLength(len);
                fs.Close();
			}
        }
        public virtual string make(FileInf file)
        {
            //文件名称为空 => 抛出异常
            if (string.IsNullOrEmpty(file.pathSvr)) throw new IOException("pathSvr is empty");
            if (!LongPathFile.Exists(file.pathSvr))
            {
                var pos = file.pathSvr.LastIndexOf('\\');
                if (-1 == pos) pos = file.pathSvr.LastIndexOf('/');
                var dir = file.pathSvr.Substring(0, pos);
                //自动创建目录
                if (!LongPathDirectory.Exists(dir))
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("路径不存在：{0}", dir));
                    PathTool.createDirectory(dir);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("路径存在：{0}", dir));
                }

                var fs = LongPathFile.Open(file.pathSvr, FileMode.Create, FileAccess.Write);
                fs.SetLength(file.lenLoc);
                fs.Close();
            }
            return "";
        }

        /// <summary>
        /// 续传文件
        /// </summary>
        /// <param name="block">文件块</param>
        /// <param name="path">远程文件完整路径。d:\www\web\upload\201204\10\md5.exe</param>
        public bool write(string path,long fileLen, long offset, ref Stream block)
		{
			//上传的文件大小不为空
			if (block.Length > 0)
			{
                //创建文件
                if (offset == 0) this.make(path, fileLen);

                //文件已存在，写入数据
                FileStream fs = LongPathFile.Open(path, FileMode.Open, FileAccess.Write, FileShare.Write);
				fs.Seek(offset, SeekOrigin.Begin);
                //重置位置
                block.Seek(0, SeekOrigin.Begin);
				byte[] ByteArray = new byte[block.Length];
				block.Read(ByteArray, 0, (int)block.Length);
				fs.Write(ByteArray, 0, (int)block.Length);
				fs.Flush();
				fs.Close();
				return true;
			}
			return false;
        }

        /// <summary>
        /// 续传文件，参数：pathSvr,blockOffset
        /// </summary>
        /// <param name="fileRange">文件块</param>
        /// <param name="path">远程文件完整路径。d:\www\web\upload\201204\10\md5.exe</param>
        public virtual string write(FileInf file, Stream fileStm)
        {
            if (!File.Exists(file.pathSvr)) throw new IOException("io error pathSvr not exist");
            //文件已存在，写入数据
            FileStream fs = LongPathFile.Open(file.pathSvr, FileMode.Open, FileAccess.Write, FileShare.Write);
            fs.Seek(file.blockOffset, SeekOrigin.Begin);
            byte[] ByteArray = new byte[fileStm.Length];
            fileStm.Seek(0, SeekOrigin.Begin);
            fileStm.Read(ByteArray, 0, (int)fileStm.Length);
            fs.Write(ByteArray, 0, (int)fileStm.Length);
            fs.Flush();
            fs.Close();
            return file.pathSvr;
        }
    }
}
